package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.MessageDTO;
import com.yuelao.yuelao_backend.entity.Conversation;
import com.yuelao.yuelao_backend.entity.Message;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.mapper.MessageMapper;
import com.yuelao.yuelao_backend.mapper.UserMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.ConversationService;
import com.yuelao.yuelao_backend.service.MessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 私聊消息Service实现类
 * 重构说明：适配新的Conversation + Message表结构，只处理私聊消息
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    private UserMapper userMapper;
    
    @Resource
    private ConversationService conversationService;
    
    @Resource
    private AchievementService achievementService;

    @Override
    public List<MessageDTO> getChatHistory(Long currentUserId, Long targetUserId, int pageNum, int pageSize) {
        // 检查用户是否存在
        User currentUser = userMapper.selectById(currentUserId);
        User targetUser = userMapper.selectById(targetUserId);
        if (currentUser == null || targetUser == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 获取或创建会话
        Conversation conversation = conversationService.getOrCreateConversation(currentUserId, targetUserId);

        Page<Message> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getConversationId, conversation.getId())
                    .eq(Message::getIsRevoked, false)
                    .orderByDesc(Message::getCreatedAt);

        Page<Message> messagePage = page(page, queryWrapper);
        return messagePage.getRecords().stream()
                .map(this::convertToMessageDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMessage(Long senderId, Long receiverId, String messageType,
                               String content, String mediaUrl) {
        // 检查发送者和接收者是否存在
        User sender = userMapper.selectById(senderId);
        User receiver = userMapper.selectById(receiverId);
        if (sender == null || receiver == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "发送者或接收者不存在");
        }

        // 获取或创建会话
        Conversation conversation = conversationService.getOrCreateConversation(senderId, receiverId);

        // 创建消息
        Message message = new Message();
        message.setConversationId(conversation.getId());
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setMessageType(messageType);
        message.setContent(content);
        message.setMediaUrl(mediaUrl);
        message.setIsRead(false);
        message.setIsRevoked(false);
        message.setCreatedAt(LocalDateTime.now());
        
        boolean saved = save(message);
        
        if (saved) {
            // 更新会话的最后消息ID和时间
            conversationService.updateLastMessage(conversation.getId(), message.getId());
            
            // 检查消息相关成就
            achievementService.checkMessageAchievements(senderId, false);
        }
        
        return saved;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsRead(Long messageId) {
        Message message = getById(messageId);
        if (message == null) {
            return false;
        }
        
        if (message.getIsRead() != null && message.getIsRead()) {
            return true; // 已经已读
        }
        
        message.setIsRead(true);
        message.setReadAt(LocalDateTime.now());
        return updateById(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean revokeMessage(Long messageId, Long userId) {
        Message message = getById(messageId);
        if (message == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "消息不存在");
        }
        
        // 只有发送者才能撤回
        if (!message.getSenderId().equals(userId)) {
            throw new BizException(ErrorCode.NO_AUTH_ERROR, "只能撤回自己的消息");
        }
        
        // 检查是否超过2分钟
        if (message.getCreatedAt() != null && 
            LocalDateTime.now().isAfter(message.getCreatedAt().plusMinutes(2))) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "超过2分钟的消息无法撤回");
        }
        
        message.setIsRevoked(true);
        message.setRevokedAt(LocalDateTime.now());
        return updateById(message);
    }

    @Override
    public long getUnreadMessageCount(Long conversationId, Long userId) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId, conversationId)
               .eq(Message::getReceiverId, userId)
               .eq(Message::getIsRead, false)
               .eq(Message::getIsRevoked, false);
        return count(wrapper);
    }

    @Override
    public MessageDTO convertToMessageDTO(Message message) {
        if (message == null) {
            return null;
        }
        MessageDTO dto = new MessageDTO();
        BeanUtils.copyProperties(message, dto);

        // 填充发送者昵称和头像
        User sender = userMapper.selectById(message.getSenderId());
        if (sender != null) {
            dto.setSenderNickname(sender.getNickname());
            dto.setSenderAvatar(sender.getAvatar());
        }

        // 填充接收者昵称和头像
        User receiver = userMapper.selectById(message.getReceiverId());
        if (receiver != null) {
            dto.setReceiverNickname(receiver.getNickname());
            dto.setReceiverAvatar(receiver.getAvatar());
        }

        return dto;
    }
}
